﻿using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Windows.Forms;
using Autodesk.Revit.Attributes;
using Autodesk.Revit.DB;
using Autodesk.Revit.DB.Architecture;
using Autodesk.Revit.UI;
using YArchitech.Controls;
using YArchitech.LIB;
using YArchitech.ProgressBar;
using HYCodeBase.WinForm;
using HYView;
using LightingEquipmentLay.RegionSearch;
using LightingEquipmentLay.Utility;
using RegionSplittor.Utils;

namespace HYLightingEquipmentLay
{
	[Transaction(TransactionMode.Manual)]
	public class CmdTestFlatPlateFloorBeamCells : IExternalCommand
	{
		public Result Execute(ExternalCommandData commandData, ref string message, ElementSet elements)
		{
			if (SwitchView.SetUsableView(CmdViewType.FloorPlan, commandData) != Autodesk.Revit.UI.Result.Succeeded)
			{
				return Autodesk.Revit.UI.Result.Failed;
			}
			ProgressBarForm progressBarForm = new ProgressBarForm(6, ProgressBarStyle.Blocks, true);
			try
			{
				UIDocument activeUIDocument = commandData.Application.ActiveUIDocument;
				Document doc = activeUIDocument.Document;
                Document linkedDocByCurDoc = RegionSplittor.Utils.LinkDocumentOperator.GetLinkedDocByCurDoc(doc, "A");
                Document linkedDocByCurDoc2 = RegionSplittor.Utils.LinkDocumentOperator.GetLinkedDocByCurDoc(doc, "S");
				if (linkedDocByCurDoc2 == null || linkedDocByCurDoc == null)
				{
					progressBarForm.Close();
					YJKMessageBox.Show("项目中不存在建筑或结构的链接文件！");
					return Autodesk.Revit.UI.Result.Failed;
				}
				commandData.Application.Application.FailuresProcessing += DeleteWarning.OnFailuresProcessing;
                List<List<CurveLoop>> list = DrawZoneCom.DrawZoneCom.DrawZoneManual(commandData.Application, new HYCodeBase.WinForm.WindowHandle(Process.GetCurrentProcess().MainWindowHandle));
				if (list.Count < 1)
				{
					progressBarForm.Close();
					return Autodesk.Revit.UI.Result.Succeeded;
				}
				if (list.First<List<CurveLoop>>().Count < 1)
				{
					progressBarForm.Close();
					return Autodesk.Revit.UI.Result.Succeeded;
				}
				List<CurveLoop> loops = list.First<List<CurveLoop>>();
				progressBarForm.Text = "无梁照明布置中...";
				progressBarForm.ShowInTaskbar = false;
				progressBarForm.Show(this._wndRevit);
				progressBarForm.Text = "正在获取信息...";
				progressBarForm.RefreshProgressBar();
				List<FamilyInstance> intersectsColumns = this.GetIntersectsColumns(linkedDocByCurDoc2, loops);
				LightingLayoutOper.InitLaneLightStyle();
				progressBarForm.Text = "正在初始化灯具类型...";
				progressBarForm.RefreshProgressBar();
				GarageLaySettingAuxiliary garageLaySettingAuxiliary = new GarageLaySettingAuxiliary();
				string empty = string.Empty;
				FamilySymbol symbol = garageLaySettingAuxiliary.GetLayLight(doc, ref empty);
				if (symbol == null)
				{
					progressBarForm.Close();
					YJKMessageBox.Information(empty);
					return Autodesk.Revit.UI.Result.Succeeded;
				}
				progressBarForm.Text = "正在获取车库电气设置信息...";
				progressBarForm.RefreshProgressBar();
				GarageLineParam garageLineInterfaceInfo = garageLaySettingAuxiliary.GetGarageLineInterfaceInfo();
				RegionSearchManager.m_strLightLayStyle = garageLineInterfaceInfo.LightLayStyle;
				Level genLevel = doc.ActiveView.GenLevel;
				progressBarForm.Text = "正在初始化信息...";
				progressBarForm.RefreshProgressBar();
				List<Curve> lstLanes = RegionSearchManager.InitLaneRegionData(linkedDocByCurDoc, genLevel);
				List<FamilyInstance> lstParkings = RegionSearchManager.InitParkingRegionData(linkedDocByCurDoc, genLevel);
				List<Room> lstRooms = RegionSearchManager.InitRoomRegionData(linkedDocByCurDoc, genLevel);
				List<Grid> lstGrids = RegionSearchManager.InitGridData(linkedDocByCurDoc2);
				progressBarForm.Text = "正在识别网格...";
				progressBarForm.RefreshProgressBar();
				List<RegionFuncInfo> docFlatPlateFloorCellFuncInfos = RegionSearchManager.GetDocFlatPlateFloorCellFuncInfos(doc, genLevel, intersectsColumns, lstGrids, lstLanes, lstParkings, lstRooms, loops);
				progressBarForm.Text = "正在布置灯具...";
				progressBarForm.RefreshProgressBar();
				List<KeyValuePair<LightingLayoutOper.ComparableLine, List<XYZ>>> lineIntersectionInfos = LightingLayoutOper.GetLineIntersectionInfos(RegionSearchManager.InitLinearCombineLaneData(linkedDocByCurDoc, genLevel));
				List<RegionFuncInfo> beamLaneRegions = (from e in docFlatPlateFloorCellFuncInfos
				where e.ERegionFunc == ERegionFunc.eLane
				select e).ToList<RegionFuncInfo>();
				LightingLayoutOper.m_strLightLayStyle = garageLineInterfaceInfo.LightLayStyle;
				LightingLayoutOper.DoLightingLayoutByLanes(genLevel, beamLaneRegions, lineIntersectionInfos, false).ForEach(delegate(LightingLayoutOper.LightingInfo e)
				{
					Common.CreateLightingFamilyInstance(doc, e, e.Angle, symbol);
				});
				LightingLayoutOper.DoLightingLayoutByParkings((from e in docFlatPlateFloorCellFuncInfos
				where e.ERegionFunc == ERegionFunc.eParking
				select e).ToList<RegionFuncInfo>()).ForEach(delegate(LightingLayoutOper.LightingInfo e)
				{
					Common.CreateLightingFamilyInstance(doc, e, e.Angle, symbol);
				});
			}
			catch (Exception ex)
			{
				progressBarForm.Close();
				YJKMessageBox.Show(ex.ToString());
			}
			return Autodesk.Revit.UI.Result.Succeeded;
		}

		private FilledRegion CreateFilledRegion(Autodesk.Revit.DB.Document doc, CurveLoop loopCvs, FilledRegionType type)
		{
			FilledRegion result = null;
			List<CurveLoop> list = new List<CurveLoop>();
			list.Add(loopCvs);
			Transaction transaction = new Transaction(doc, "CreateFilledRegion");
			try
			{
				transaction.Start();
				result = FilledRegion.Create(doc, type.Id, doc.ActiveView.Id, list);
				transaction.Commit();
			}
			catch
			{
				transaction.RollBack();
			}
			return result;
		}

		private List<FamilyInstance> GetIntersectsColumns(Autodesk.Revit.DB.Document doc, List<CurveLoop> loops)
		{
			List<FamilyInstance> result = new List<FamilyInstance>();
			try
			{
				Solid solid = GeometryCreationUtilities.CreateExtrusionGeometry(loops, XYZ.BasisZ, 3.2808398950131235);
				ElementFilter elementFilter = new ElementMulticategoryFilter(new List<BuiltInCategory>
				{
					(Autodesk.Revit.DB.BuiltInCategory)(-2000100),
					(Autodesk.Revit.DB.BuiltInCategory)(-2001330)
				});
				ElementIntersectsSolidFilter elementIntersectsSolidFilter = new ElementIntersectsSolidFilter(solid);
				LogicalAndFilter logicalAndFilter = new LogicalAndFilter(elementFilter, elementIntersectsSolidFilter);
				result = new FilteredElementCollector(doc).WherePasses(logicalAndFilter).Cast<FamilyInstance>().ToList<FamilyInstance>();
			}
			catch (Exception)
			{
			}
			return result;
		}

		private YJKWindowHandle _wndRevit;
	}
}
